/*
 * @Author: 糊涂的老知青
 * @Date: 2021-10-30
 * @Version: 1.0.0
 * @Description:
 */
package config

import (
	"fmt"
	"time"

	"github.com/spf13/viper"
)

type AppConfig struct {
	ServerConfig `mapstructure:"server"`
	Database     `mapstructure:"database"`
	RedisConfig  `mapstructure:"redis"`
	JwtConfig    `mapstructure:"jwt"`
	LogConfig    `mapstructure:"log"`
}

type Database struct {
	Type        string `mapstructure:"type"`
	Host        string `mapstructure:"host"`
	UserName    string `mapstructure:"username"`
	Password    string `mapstructure:"password"`
	Database    string `mapstructure:"database"`
	MaxOpenConn int    `mapstructure:"max_open_conn"`
	MaxIdleConn int    `mapstructure:"max_idle_conn"`
	IsMigration bool   `mapstructure:"is_migration"`
}

type ServerConfig struct {
	RunMode           string
	HttpPort          int
	ReadTimeout       time.Duration
	WriteTimeout      time.Duration
	UseMultiTenancy   bool
	DefaultAvatar     string
	ServiceModuleCode string
}

type RedisConfig struct {
	RedisHost     string `mapstructure:"RedisHost"`
	RedisPwd      string `mapstructure:"RedisPwd"`
	RedisDB       int    `mapstructure:"RedisDB"`
	RedisPoolName string `mapstructure:"RedisPoolName"`
}

type JwtConfig struct {
	JwtIssuer     string `mapstructure:"JwtIssuer"`
	JwtSecret     string `mapstructure:"JwtSecret"`
	JwtExpireDate int    `mapstructure:"JwtExpireDate"`
}

type LogConfig struct {
	ApplicationName   string `mapstructure:"ApplicationName"`
	UseElasticSearch  bool   `mapstructure:"UseElasticSearch"`
	ElasticSearchUrl  string `mapstructure:"ElasticSearchUrl"`
	ElasticSearchUser string `mapstructure:"ElasticSearchUser"`
	ElasticSearchPwd  string `mapstructure:"ElasticSearchPwd"`
}

var Config = &AppConfig{}

var ViperConfig = &viper.Viper{}

// Init 初始化配置文件
func init() {
	ViperConfig = viper.New()
	ViperConfig.AddConfigPath("./config/") // 文件所在目录
	ViperConfig.SetConfigName("config")    // 文件名
	ViperConfig.SetConfigType("ini")       // 文件类型

	if err := ViperConfig.ReadInConfig(); err != nil {
		if _, ok := err.(viper.ConfigFileNotFoundError); ok {
			fmt.Println("找不到配置文件..")
		} else {
			fmt.Println("配置文件出错..")
		}
	}

	ViperConfig.Unmarshal(Config)
}
